// app
package bootstrap

import (
	"github.com/Unknwon/goconfig"
	_ "github.com/aiwuTech/fileLogger"
	"github.com/codegangsta/martini"
	"github.com/martini-contrib/auth"
	"github.com/martini-contrib/render"
	"martini_template/componnet"
	"strconv"
	"time"
)

var App *martini.ClassicMartini
var appConfig *goconfig.ConfigFile

//初始化Martini App
func InitApp() {
	loadConfig()
	App = martini.Classic()
	App.Logger(componnet.Slogger)
	if componnet.ENV == componnet.ENV_PROD {
		martini.Env = martini.Prod
	} else {
		martini.Env = martini.Dev
	}
	RegisterService()
	RegisterMiddleware()
}

//加载配置文件
func loadConfig() {
	appConfig = componnet.AppConfig
}

//注册中间件
func RegisterMiddleware() {
	App.Use(render.Renderer(render.Options{Charset: "UTF-8", IndentJSON: false}))
	//http请求认证
	if componnet.ENV == "prod" {
		App.Use(auth.BasicFunc(authFn))
	}
	//静态目录
	//	staticDirectory, gerr := appConfig.GetValue(componnet.ENV, "static_directory")
	//	if gerr != nil {
	//		staticDirectory = "static"
	//	}
	//	App.Use(martini.Static(staticDirectory))
}

func authFn(usernameAt string, passwordAt string) bool {
	username, password := createAuthUser()
	if username == usernameAt {
		if password == passwordAt {
			return true
		} else {
			return false
		}
	} else {
		return false
	}
}
func createAuthUser() (string, string) {
	var username string
	username = strconv.Itoa(time.Now().Year()) + "-" + strconv.Itoa(time.Now().Day())
	subTimeStamp := strconv.FormatInt(time.Now().Unix(), 10)
	runeStr := []rune(subTimeStamp)
	username = username + string(runeStr[0:6])
	username, _ = componnet.AesEncrypt(username)
	password, _ := componnet.AesEncrypt("_" + username + "hdj_xzd")
	return username, password
}

//注册服务
func RegisterService() {
	//注册文件日志
	//App.Map(componnet.Alogger)
	//注册系统配置
	App.Map(appConfig)
	//注册系统环境变量
	App.Map(componnet.ENV)
	//注册返回的json结构
	var resJson componnet.ResponsJson
	App.Map(resJson)
}

//执行App
func AppRun() {
	host, _ := appConfig.GetValue(componnet.ENV, "host")
	port, _ := appConfig.GetValue(componnet.ENV, "port")
	App.RunOnAddr(host + ":" + port)
}
